package com.yuelao.yuelao_backend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuelao.yuelao_backend.common.BizException;
import com.yuelao.yuelao_backend.common.ErrorCode;
import com.yuelao.yuelao_backend.entity.UserLike;
import com.yuelao.yuelao_backend.enums.SystemMessageType;
import com.yuelao.yuelao_backend.mapper.UserLikeMapper;
import com.yuelao.yuelao_backend.service.AchievementService;
import com.yuelao.yuelao_backend.service.SystemMessageService;
import com.yuelao.yuelao_backend.service.UserLikeService;
import com.yuelao.yuelao_backend.service.UserMatchService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import jakarta.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户喜欢Service实现类
 * 重构说明：从UserRelationship拆分出来，专门处理用户喜欢功能
 */
@Service
public class UserLikeServiceImpl extends ServiceImpl<UserLikeMapper, UserLike> implements UserLikeService {

    @Resource
    private UserMatchService userMatchService;
    
    @Resource
    private AchievementService achievementService;
    
    @Resource
    private SystemMessageService systemMessageService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean likeUser(Long userId, Long likedUserId) {
        if (userId.equals(likedUserId)) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "不能喜欢自己");
        }

        // 检查是否已经喜欢过
        if (hasLiked(userId, likedUserId)) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "已经喜欢过该用户");
        }

        // 创建喜欢记录
        UserLike like = new UserLike();
        like.setUserId(userId);
        like.setLikedUserId(likedUserId);
        like.setIsSuper(false);
        like.setCreatedAt(LocalDateTime.now());

        // 检查对方是否也喜欢自己
        boolean isMutual = hasLiked(likedUserId, userId);
        like.setIsMutual(isMutual);
        
        boolean saved = save(like);
        
        // 如果互相喜欢，创建配对
        if (saved && isMutual) {
            // 更新对方的记录为互相喜欢
            LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserLike::getUserId, likedUserId)
                   .eq(UserLike::getLikedUserId, userId);
            UserLike reverseLike = getOne(wrapper);
            if (reverseLike != null) {
                reverseLike.setIsMutual(true);
                updateById(reverseLike);
            }
            
            // 创建配对记录
            userMatchService.createMatch(userId, likedUserId, false);
        }
        
        // 检查发送喜欢相关成就
        if (saved) {
            achievementService.checkSendLikeAchievements(userId, false);
            // 检查获得喜欢相关成就
            achievementService.checkGetLikeFromUserAchievements(likedUserId);
            
            // 创建系统消息通知被喜欢的用户
            java.util.Map<String, Object> extraData = new java.util.HashMap<>();
            extraData.put("fromUserId", userId);
            systemMessageService.createMessage(likedUserId, SystemMessageType.LIKE, "有人喜欢了你", "有人喜欢了你，快去看看吧", extraData);
        }
        
        return saved;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean superLikeUser(Long userId, Long likedUserId) {
        if (userId.equals(likedUserId)) {
            throw new BizException(ErrorCode.PARAMS_ERROR, "不能喜欢自己");
        }

        // 检查是否已经喜欢过
        if (hasLiked(userId, likedUserId)) {
            throw new BizException(ErrorCode.OPERATION_ERROR, "已经喜欢过该用户");
        }

        // 创建超级喜欢记录
        UserLike like = new UserLike();
        like.setUserId(userId);
        like.setLikedUserId(likedUserId);
        like.setIsSuper(true);
        like.setCreatedAt(LocalDateTime.now());

        // 检查对方是否也喜欢自己
        boolean isMutual = hasLiked(likedUserId, userId);
        like.setIsMutual(isMutual);
        
        boolean saved = save(like);
        
        // 如果互相喜欢，创建配对
        if (saved && isMutual) {
            // 更新对方的记录为互相喜欢
            LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(UserLike::getUserId, likedUserId)
                   .eq(UserLike::getLikedUserId, userId);
            UserLike reverseLike = getOne(wrapper);
            if (reverseLike != null) {
                reverseLike.setIsMutual(true);
                updateById(reverseLike);
            }
            
            // 创建配对记录（标记为super match）
            userMatchService.createMatch(userId, likedUserId, true);
        }
        
        // 检查发送超级喜欢相关成就
        if (saved) {
            achievementService.checkSendLikeAchievements(userId, true);
            // 检查获得喜欢相关成就
            achievementService.checkGetLikeFromUserAchievements(likedUserId);
            
            // 创建系统消息通知被超级喜欢的用户
            java.util.Map<String, Object> extraData = new java.util.HashMap<>();
            extraData.put("fromUserId", userId);
            systemMessageService.createMessage(likedUserId, SystemMessageType.SUPER_LIKE, "有人超级喜欢了你", "有人超级喜欢了你，快去看看吧", extraData);
        }
        
        return saved;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean unlikeUser(Long userId, Long likedUserId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId)
               .eq(UserLike::getLikedUserId, likedUserId);
        
        UserLike like = getOne(wrapper);
        if (like == null) {
            return true; // 已经取消过了
        }
        
        // 如果是互相喜欢，需要更新对方的记录和删除配对
        if (like.getIsMutual() != null && like.getIsMutual()) {
            // 更新对方的记录
            LambdaQueryWrapper<UserLike> reverseWrapper = new LambdaQueryWrapper<>();
            reverseWrapper.eq(UserLike::getUserId, likedUserId)
                          .eq(UserLike::getLikedUserId, userId);
            UserLike reverseLike = getOne(reverseWrapper);
            if (reverseLike != null) {
                reverseLike.setIsMutual(false);
                updateById(reverseLike);
            }
            
            // 删除配对记录
            userMatchService.removeMatch(userId, likedUserId);
        }
        
        return remove(wrapper);
    }

    @Override
    public boolean hasLiked(Long userId, Long likedUserId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId)
               .eq(UserLike::getLikedUserId, likedUserId);
        return count(wrapper) > 0;
    }

    @Override
    public boolean isMutualLike(Long userId1, Long userId2) {
        return hasLiked(userId1, userId2) && hasLiked(userId2, userId1);
    }

    @Override
    public List<Long> getMyLikes(Long userId, int page, int size) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> pageObj = 
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);
        
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId)
               .orderByDesc(UserLike::getCreatedAt);
        
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> result = page(pageObj, wrapper);
        return result.getRecords().stream()
                .map(UserLike::getLikedUserId)
                .collect(java.util.stream.Collectors.toList());
    }

    @Override
    public List<Long> getWhoLikesMe(Long userId, int page, int size) {
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> pageObj = 
            new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page, size);
        
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getLikedUserId, userId)
               .orderByDesc(UserLike::getCreatedAt);
        
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<UserLike> result = page(pageObj, wrapper);
        return result.getRecords().stream()
                .map(UserLike::getUserId)
                .collect(java.util.stream.Collectors.toList());
    }

    @Override
    public long countMyLikes(Long userId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId);
        return count(wrapper);
    }

    @Override
    public long countWhoLikesMe(Long userId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getLikedUserId, userId);
        return count(wrapper);
    }

    @Override
    public long countMutualLikes(Long userId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId)
               .eq(UserLike::getIsMutual, true);
        return count(wrapper);
    }

    @Override
    public long countSuperMatches(Long userId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getUserId, userId)
               .eq(UserLike::getIsSuper, true)
               .eq(UserLike::getIsMutual, true);
        return count(wrapper);
    }

    @Override
    public long countWhoSuperLikesMe(Long userId) {
        LambdaQueryWrapper<UserLike> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserLike::getLikedUserId, userId)
               .eq(UserLike::getIsSuper, true);
        return count(wrapper);
    }
}

